package x.y.z.repository;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;
import x.y.z.bean.KeyValue;
import x.y.z.mapper.KeyValueMapper;

import java.sql.Types;
import java.util.Collections;
import java.util.List;
import java.util.Map;
@Repository
public class KeyValDaoImpl implements KeyValDao  {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public int add(KeyValue entity){
        String sql = "INSERT INTO `dm`.`kvs` ( `tkey`, `tval`) VALUES ( :tkey, :tval)";
        NamedParameterJdbcTemplate npjt = new NamedParameterJdbcTemplate(this.jdbcTemplate.getDataSource());
        return npjt.update(sql,new BeanPropertySqlParameterSource(entity));
    }
    @Override
    public int update(KeyValue entity){
        String sql = "UPDATE `dm`.`kvs` SET `tkey`=?, `tval`='aa' WHERE (`id`=?)";
        Object[] args = {entity.getTkey(),entity.getTval(), entity.getId()};
        int[] argTypes = {Types.VARCHAR,Types.VARCHAR,Types.INTEGER};
        return this.jdbcTemplate.update(sql,args,argTypes);

    }
    @Override
    public int deleteById(Long id){
        String sql = "delete from `dm`.`kvs`where t.id = ?";
        Object[] args = {id};
        int[] argTypes = {Types.INTEGER};
        return this.jdbcTemplate.update(sql,args,argTypes);
    }
    @Override
    public KeyValue getById(Long id){
        String sql = "select * from `dm`.`kvs`where t.id = ?";
        Object[] args = {id};
        int[] argTypes = {Types.INTEGER};
        List<KeyValue> list = this.jdbcTemplate.query(sql,args,argTypes,new KeyValueMapper());
        if(list != null && list.size()>0){
            return list.get(0);
        }else{
            return null;
        }
    }
    @Override
    public List<KeyValue> all(){
        String sql = "select * from `dm`.`kvs`";
        Object[] args = {};
        int[] argTypes = {};
        List<KeyValue> list = this.jdbcTemplate.query(sql,args,argTypes,new KeyValueMapper());
        return list;
    }
    @Override
    public List<Map<String,Object>> lsitMap(){
        String sql = "select * from `dm`.`kvs`";
        return this.jdbcTemplate.queryForList(sql);
    }
}
